/**
 * Created by PC on 11/15/14.
 */
$(document).ready(function(){
    // render
    loadData();
    // event
    bindEvent();
});

function loadData() {
    ISS.BACKEND.request({
        url: '../../service/admin/getDataRegister',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        },
        type: 'GET',
        dataType: 'json',
        success: function (data) {
            var responseContent = data.responseObject;
            mapLevelToView(responseContent);
        }
    });

    ISS.BACKEND.request({
        url: '../../service/admin/getMemberInfor',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        },
        type: 'GET',
        dataType: 'json',
        success: function (data) {
            var responseContent = data.responseObject;
            mapMemberInforToView(responseContent);
        }
    });
}

function bindEvent() {
    ISS.EVENT.bindEvent('#RegeditFormMember_submit', 'click', function () {
        clearValidate();
        if(validate()){
            sendInfo();
        }
        else {
            var htmlText = '<div class="box s-error mbs msgBox l-pageWrapper mbm">\
                                <div class="pam">Đăng kí tài khoản thất bại</div>\
                            </div>';
            ISS.DOM.before('.l-register__benefits', htmlText);
        }
    });

    ISS.EVENT.bindEvent('#RegeditFormMemberCommon_Modified', 'click', function () {
        toEditPage();
    });

    ISS.EVENT.bindEvent('#RegeditFormMemberCommon_Delete', 'click', function () {
        deleteMember();
    });
}

function deleteMember() {
    var user = {};
    var listUser = [];
    var lstThanhVien=[];

    ISS.DOM.forEach('#form-AdLawCommon input[type="checkbox"]:checked', function(){
        listUser.push($(this).val());
    });
    if(listUser.length > 0) {
        for(var i =0; i < listUser.length; i++) {
            user.maTV = listUser[i];
            lstThanhVien.push(user);
        }
           ISS.DOM.forEach('#form-AdLawCommon input[type="checkbox"]:checked', function(){
               user.maTV = $(this).val();
               listUser.push(user);
           });

           ISS.BACKEND.request({
               url: ISS.SESSION.getSession('contextPath') + '/service/admin/deleteRegisterMember',
               headers: {
                   'Accept': 'application/json',
                   'Content-Type': 'application/json'
               },
               type: 'POST',
               dataType: 'json',
               data: JSON.stringify(lstThanhVien),
               success: function (data) {
                   var responseContent = data.responseObject;
                   mapMemberInforToView(responseContent);
               }
           });
    }
    else {
        alert('Bạn chưa chọn');
    }

}

function validate() {
    var email, result;
    email = ISS.DOM.getVal('#RegeditFormMember_email');

    if(!email) {
        ISS.DOM.addClass('#RegistrationForm_email', 'error');
        result = false;
    }

    if(email) {
            if(!ISS.VALIDATION.validateEmail(email, true)){
                ISS.DOM.addClass('#RegistrationForm_email', 'error');
                result = false;
            }
            else {
                result = true;
            }
        }
    return result;
}

function sendInfo() {
    var user = {};
    var measurement = {};
    user.maTV = ISS.DOM.getVal('#RegeditFormMember_code');
    measurement.maSDCoThe = ISS.DOM.getVal('#RegeditFormMember_measurement');
    user.soDoCoThe = measurement;
    user.ten = ISS.DOM.getVal('#RegeditFormMember_firstname');
    user.ho = ISS.DOM.getVal('#RegeditFormMember_lastname');
    user.ngaySinh = ISS.DOM.getVal('#RegeditFormMember_birthday');
    user.gioiTinh = ISS.DOM.getVal('#RegeditFormMember_sexual');
    user.email = ISS.DOM.getVal('#RegeditFormMember_email');
    user.soDT = ISS.DOM.getVal('#RegeditFormMember_phonenumber');
    user.diaChi = ISS.DOM.getVal('#RegeditFormMember_address');

    ISS.BACKEND.request({
        url: '../../service/admin/registerMember',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        },
        type: 'POST',
        dataType: 'json',
        data: JSON.stringify(user),
        success: function (data) {
            var responseContent = data.responseObject;

        }
    });
}

function toEditPage() {
    var _maTV = []
    ISS.DOM.forEach('#form-AdLawCommon input[type="checkbox"]:checked', function(){
        _maTV.push($(this).val());
    });

    if(_maTV.length == 1) {
        var _url = '/service/admin/toRegisterMemberPage/' + _maTV[0] + '.';
        ISS.WINDOW.location(_url);
    }
    else {
        alert('Không được chọn hơn một dòng')
    }
}

function clearValidate() {
    ISS.DOM.removeClass('#RegistrationForm_email', 'error');
    ISS.DOM.removeClass('#RegistrationForm_password', 'error');
}

function mapLevelToView(level) {
    var html = '<option selected="selected" value="popularity">Mời chọn...</option>';
    for(var i=0; i<level.length; i++) {
        html += '<option value="' + level[i].maCB + '">' + level[i].tenCB + '</option>';
    }
    ISS.DOM.html('#RegeditFormMember_level', html);
}

function mapMemberInforToView(infor) {
    var rows = infor.length;
    var columns = 1;
    var str = '';
    str += '<table id="MemberTable" class="tableMemberWidth align-center">';
    str += '<thead>';
    str += '   <tr>';
    str += '       <th class="columnMemberSTT">STT</th>';
    str += '       <th class="columnMemberStick">Tick</th>';
    str += '       <th class="columnMemberEmail">Email</th>';
    str += '       <th class="columnMemberLastName">Họ</th>';
    str += '       <th class="columnMemberFirstName">Tên</th>';
    str += '       <th class="columnMemberDate">Ngày sinh</th>';
    str += '       <th class="columnMemberSexual">Giới tính</th>';
    str += '       <th class="columnMemberAddress">Địa chỉ</th>';
    str += '       <th class="columnMemberPhone">Số điện thoại</th>';
    str += '   </tr>';
    str += '</thead>';
    str += '<tbody>';
    for(var i = 0; i < rows; i++){
        if (i%2==0){
            str += '<tr onmouseover="set_hover(this);" onmouseout="remove_hover(this)" id="showData" class="column-Light tableTransparent">';
        }else{
            str += '<tr onmouseover="set_hover(this);" onmouseout="remove_hover(this)" id="showData" class="column-Light tableTransparent">';
        }

        for (var j = 0; j < columns; j++){
            str += '<td class="columnMemberSTT tableMemberPadding">' + i + '</td>';
            str += '<td class="columnMemberStick tableMemberPadding"><input onclick="highlight_row(this)" id="' + infor[i].maTV + '" type="checkbox" value="' + infor[i].maTV + '"/></td>';
            str += '<td class="columnMemberEmail tableMemberPadding">' + infor[i].maTV + '</td>';
            str += '<td class="columnMemberLastName tableMemberPadding">' + infor[i].ho + '</td>';
            str += '<td class="columnMemberFirstName tableMemberPadding">' + infor[i].ten + '</td>';
            str += '<td class="columnMemberDate tableMemberPadding">' + ISS.DATE.getFullDate(new Date(infor[i].ngaySinh)) + '</td>';
            str += '<td class="columnMemberSexual tableMemberPadding">' + infor[i].gioiTinh + '</td>';
            str += '<td class="columnMemberAddress tableMemberPadding" title="' + infor[i].diaChi + '">' + infor[i].diaChi.trunc(23,true) + '</td>';
            str += '<td class="columnMemberPhone tableMemberPadding">' + infor[i].soDT + '</td>';
        }
        str += '</tr>';
    }
    str +=   '</tbody>';
    str += '</table>';
    ISS.DOM.html('#RegeditFormMemberCommon_All', str);
}